/// <reference path="../../typings/request/request.d.ts" />
var q = require('q');
var request = require('request').defaults({
    json: true
});


var config = require('./../config.json');
var cacheHelper = require('./../service/redisHelper.js');
var Project = function(param) {
    this.name = "";
    if (typeof(param) === 'object') {
        this.center = param.remark ? JSON.parse(param.remark) : null; //项目的位置中心
        param.remark = undefined; //移除原来的remark属性 
    } else if (typeof(param - 0) === 'number') {
        this.prjId = param;
    }
};
Project.mix = function(obj) {
    for (var key in obj) {
        if (Project.prototype.hasOwnProperty(key)) {
            throw new Error('不能覆盖已有的原型方法' + key);
        }
        Project.prototype[key] = obj[key];
    }
};
//添加扩展方法
Project.mix(require('./Project.Extend.ChordStastic.js'));
Project.mix(require('./Project.Extend.MonitorPoints.js'));

Project.getAllMonitorTypes = function() {
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'GET',
        url: url + '/monitortypes/'
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(JSON.parse(body));
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

Project.getAllAutoSurveyStations = function() {
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'GET',
        url: url + '/autosurveystations/'
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(JSON.parse(body));
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};


Project.addProject = function(obj) {
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    console.log(obj);
    request({
        method: 'POST',
        url: url + '/addproject/',
        json: JSON.stringify(obj)
    }, function(error, response, body) {
        try {
            var prj = JSON.parse(body);
            if (!error && prj.PrjId) {
                defer.resolve(body);
            } else {
                defer.reject(body);
            }
        } catch (ex) {
            defer.reject(ex);
        }
    });
    return defer.promise;
};

//更新工程的地图坐标
Project.prototype.updateCenter = function(center) {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'POST',
        url: url + '/updatePrjCenter/',
        json: JSON.stringify({
            'prjId': _this.prjId,
            'center': center
        })
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            cacheHelper.updateRedisCache(_this.projectTypeCode, _this.prjId, {
                    property: "center",
                    value: JSON.parse(center)
                })
                .then(function() {
                    console.log('updateCenter刷新缓存!');
                });
            defer.resolve(true);
        } else {
            defer.resolve(false);
        }
    });
    return defer.promise;
};

//刷新redis缓存
Project.prototype.refreshProjectCache = function() {
    var _this = this;
    var url = require('./../config.json').authorUrl;
    var defer = q.defer();
    request({
        method: 'get',
        url: url + '/refreshProjects/' + _this.projectTypeCode
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(true);
        } else {
            defer.resolve(false);
        }
    });
    return defer.promise;
};

//删除本项目
Project.prototype.delete = function() {
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    var _this = this;
    request({
        method: 'delete',
        url: url + '/addproject',
        qs: {
            prjId: _this.prjId
        }
    }, function(error, response, body) {
        if (!error) {
            defer.resolve(body);
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

//删除数据点
Project.prototype.deletePoints = function(date, monitorType, location) {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'delete',
        url: url + '/DeletePointByTime/',
        qs: {
            prjId: _this.prjId,
            date: date,
            monitorType: monitorType || undefined,
            location: location || undefined
        }
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(true);
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

//获取工况列表
Project.prototype.getStatusList = function() {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'get',
        url: url + '/prjstatus/',
        qs: {
            prjId: _this.prjId
        }
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(JSON.parse(body));
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

//上传工况
Project.prototype.postStatus = function(data) {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'post',
        url: url + '/prjstatus/',
        json: JSON.stringify(data)
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            //从上传数据中构建缓存信息
            var status = {
                title: data.Title,
                detail: data.Detail,
                imagesUrl: data.StatusImgs.map(function(item) {
                    return item.Url;
                }),
                endTime: data.Date
            };

            cacheHelper.updateRedisCache(_this.projectTypeCode, _this.prjId, {
                    property: "status",
                    value: status
                })
                .then(function() {
                    console.log('postStatus刷新缓存!');
                });
            _this.refreshProjectStatusCache()
                .then(function() {
                    console.log('刷新时间轴缓存');
                });
            defer.resolve(true);
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

//删除工况
Project.prototype.deleteStatus = function(data) {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'delete',
        url: url + '/prjstatus',
        qs: {
            prjId: _this.prjId,
            date: data
        }
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            _this.refreshProjectStatusCache();
            defer.resolve(JSON.parse(body));
        } else {
            defer.reject('Fail to load!');
        }
    });
    return defer.promise;
};

//刷新工况缓存
Project.prototype.refreshProjectStatusCache = function() {
    var _this = this;
    var url = config.frontPage + "/projectstatus/";
    var defer = q.defer();
    //刷新工况,部分和全部
    request({
        method: "get",
        url: url + _this.prjId + "/true/true"
    }, function(error, response, body) {
        request({
            method: "get",
            url: url + _this.prjId + "/false/true"
        }, function() {
            if (!error && response.statusCode == 200) {
                defer.resolve();
            } else {
                defer.reject();
            }
        });
    });
    return defer.promise;
};

//上传工程概况
Project.prototype.postSummary = function(data) {
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    data.property = "PrjSummary";
    request({
        method: 'post',
        url: url + '/extraprojectinfo',
        json: JSON.stringify(data)
    }, function(error, response, body) {
        if (!error) {
            defer.resolve();
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 获取监测类型
Project.prototype.getMonitorTypes = function() {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'get',
        url: url + '/monitortypes/',
        qs: {
            prjId: _this.prjId
        }
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(JSON.parse(body));
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 上传监测类型
Project.prototype.postMonitorTypes = function(data) {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'post',
        url: url + '/monitortypes/',
        json: JSON.stringify(data)
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve();
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 获取监测点
Project.prototype.getMonitorPointsDictionary = function() {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'get',
        url: url + '/monitorpointsdictionary/',
        qs: {
            prjId: _this.prjId
        }
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(JSON.parse(body));
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 更新监测点
Project.prototype.postMonitorPointsDictionary = function(data) {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'post',
        url: url + '/monitorpointsdictionary/',
        json: JSON.stringify(data)
    }, function(error, response, body) {
        if (!error && response.statusCode == 204) {
            cacheHelper.updateRedisCache(_this.projectTypeCode, _this.prjId)
                .then(function() {
                    console.log('postMonitorPointsDictionary刷新缓存!');
                });
            defer.resolve();
        } else {
            console.log(response.statusCode);
            defer.reject();
        }
    });
    return defer.promise;
};

// 更新监测点配置
Project.prototype.postMonitorPointsConfig = function(data) {
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    var _this = this;
    request({
        method: 'post',
        url: url + '/monitorpointsconfig/',
        json: JSON.stringify(data)
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            if (!body)
                defer.reject();
            else {
                cacheHelper.updateRedisCache(_this.projectTypeCode, _this.prjId)
                    .then(function() {
                        console.log('postMonitorPointsConfig刷新缓存!');
                    });
                defer.resolve();
            }
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 获取里程环号
Project.prototype.getMileage = function() {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'get',
        url: url + '/ringnumberconfig/',
        qs: {
            prjId: _this.prjId
        }
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve();
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 更新里程环号
Project.prototype.postMileage = function(data) {
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'post',
        url: url + '/ringnumberconfig/',
        json: JSON.stringify(data)
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            if (body) {
                defer.resolve();
            } else {
                defer.reject();
            }
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 获取已绑定工程
Project.prototype.getBindProject = function() {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'get',
        url: url + '/metroprojectgroup/',
        qs: {
            prjId: _this.prjId
        }
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(JSON.parse(body));
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 绑定新的工程
Project.prototype.postBindProject = function(data) {
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'post',
        url: url + '/metroprojectgroup/',
        json: JSON.stringify(data)
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve();
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 删除绑定工况
Project.prototype.deleteBindProject = function(prjName) {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var defer = q.defer();
    request({
        method: 'delete',
        url: url + '/metroprojectgroup/',
        qs: {
            prjId: _this.prjId,
            prjName: prjName
        }
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve();
        } else {
            defer.reject();
        }
    });
    return defer.promise;
};

// 更新属性
Project.prototype.postProperties = function() {
    var _this = this;
    var url = require('./../config.json').backgroundUrl;
    var properties = ["PrjState", "TunnelType", "PrjLevel", "ConstructionCorp", "Department", "OwnerCorp"];
    return properties.reduce(function(previousValue, currentValue, index, array) { // 依次更新各个属性
            return previousValue.then(function() {
                var defer = q.defer();
                _this.property = currentValue;
                request({
                    method: 'post',
                    url: url + '/extraprojectinfo',
                    json: JSON.stringify(_this)
                }, function(error, response, body) {
                    if (!error)
                        defer.resolve();
                    else
                        defer.reject(error);
                });
                return defer.promise;
            }, function(reason) {
                return q.reject(reason);
            });
        }, q(null))
        .then(function() { // 更新是否显示在地图上
            var defer = q.defer();
            request({
                method: 'post',
                url: url + '/onoffstatus',
                json: JSON.stringify({
                    prjId: _this.prjId,
                    onOff: _this.status === 1 ? true : false
                })
            }, function(error, response, body) {
                if (!error && response.statusCode == 200)
                    defer.resolve();
                else
                    defer.reject();
            });
            return defer.promise;
        }, function(reason) {
            return q.reject(reason);
        });
};

//获取布点图
Project.prototype.getLayers = function() {
    var _this = this;
    var url = require('./../config.json').apiUrl;
    var defer = q.defer();
    request({
        method: 'get',
        url: url + '/getprojectlayers?prjId=' + _this.prjId
    }, function(error, response, body) {
        if (!error && response.statusCode == 200)
            defer.resolve(body);
        else
            defer.reject();
    });
    return defer.promise;
};

//上传布点图
Project.prototype.postLayers = function(data) {
    var _this = this;
    var url = require('./../config.json').apiUrl;
    var defer = q.defer();
    request({
        method: 'put',
        url: url + '/getprojectlayers/' + _this.prjId,
        json: data
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            cacheHelper.updateRedisCache(_this.projectTypeCode, _this.prjId, {
                property: "hasJsonLayer",
                value: true
            }).then(function() {
                console.log('postLayers刷新缓存!');
            });
            defer.resolve();
        } else
            defer.reject();
    });
    return defer.promise;
};


//获取项目的审核人列表,默认是单位管理员
Project.prototype.getReviewerList = function() {
    var _this = this;
    var defer = q.defer();
    var url = config.adminBaseUrl + "/project/" + _this.prjId.toString() + "/reviewerList";
    request({
        method: 'get',
        url: url
    }, function(error, response, body) {
        if (!error && response.statusCode == 200)
            defer.resolve(body);
        else
            defer.reject();
    });

    return defer.promise;
};


//向服务器发送信息,统计未审核数据的当天信息
Project.prototype._triggerUnReviewedMontinorInfo = function(data) {
    var _this = this;
    var defer = q.defer();
    var url = config.backgroundUrl + "/AfterMonitorPointsUpload";
    request({
        method: 'get',
        url: url,
        qs: data //{prjId,date}
    }, function(error, response, body) {
        if (!error && response.statusCode == 200)
            defer.resolve(body);
        else
            defer.reject();
    });
    return defer.promise;
};

Project.prototype.getReviewChange = function(params) {
    var _this = this;
    var defer = q.defer();
    var url = config.apiUrl + "/ReviewRecentChanges";
    request({
        method: 'get',
        url: url,
        qs: {
            prjId: _this.prjId,
            monitorType: params.monitorType,
            location: params.location,
            date: params.date
        }
    }, function(error, response, body) {
        if (!error && response.statusCode == 200)
            defer.resolve(body);
        else
            defer.reject();
    });
    return defer.promise;
};
module.exports = Project;
